﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
namespace XSTDZ.ERP.WebApp.Controllers
{
    [NoAuthorizated]
    public class PermissionController : Controller
    {
        private readonly IPermisstionService permissionServiceImpl = ServiceLocator.Instance.GetService<IPermisstionService>();	
        //
        // GET: /Permission/

        /// <summary>
        /// 权限列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        //新增权限（Action上的权限 粗粒度）
        [NoAuthorizated("Add")]
        public ActionResult Add()
        {
            InitOperations();

            return View();
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(PermissionDto permissionDto)
        {
            Guid addPermissionId = Guid.Empty;
            if (ModelState.IsValid)
            {
                addPermissionId=permissionServiceImpl.AddPermission(permissionDto);
                ViewBag.PostState = 9;
            }
            //InitOperations();
            ViewBag.PermissionID = addPermissionId;
            return View();
        }
        [NoAuthorizated("Edit")]
        public ActionResult Edit(Guid id)
        {
            var permission = permissionServiceImpl.GetPermission(id);
            return View(permission);
        }
        [HttpPost]
        [NoAuthorizated("Edit")]
        public ActionResult Edit(PermissionDto permissionDto)
        {
            if (ModelState.IsValid)
            {
                 permissionServiceImpl.UpdatePermission(permissionDto);
                 ViewBag.PostState = 9;
            }
            return View();
        }
        [HttpGet]
        [NoAuthorizated("DeletePermisson")]
        public ActionResult DeletePermisson(Guid id)
        {
            permissionServiceImpl.DeletePermission(id);
            return Content("ok");
        }
        //新增权限（Action上的权限 粗粒度） 页面上元素
       
        //显示权限Action页面(不可修改）
        [ChildActionOnly]
        [NoAuthorizated("PermissionInfo")]
        public ActionResult PermissionInfo(Guid permissionId)
        {
            var permissionDto = permissionServiceImpl.GetPermission(permissionId);
            InitOperations();
            return View(permissionDto);
        }
        //新增权限（指定Action内的权限，细粒度，可控制到控件）
        [HttpGet]
        [NoAuthorizated("AddUiPermisson")]
        public ActionResult AddUiPermisson(Guid permissionId)
        {
            var permissionDto = permissionServiceImpl.GetPermission(permissionId);
            ViewBag.PermissionID = permissionId;
            return View(permissionDto);
        }
        [HttpPost]
        [NoAuthorizated("AddUiPermisson")]
        public ActionResult AddUiPermisson(PermissionDto uiPermissionDto)
        {
            var permission =new PermissionDto();
            TryUpdateModel<PermissionDto>(permission);
            if (this.ModelState.IsValid)
            {
                permissionServiceImpl.AddUiPermission(permission,permission.UiPermission);
                ViewBag.PostState = 9;
            }
            return View();
        }
        [HttpGet]
        [NoAuthorizated("EditUiPermisson")]
        public ActionResult EditUiPermisson(Guid id)
        {
            ViewBag.PermissionID = id;
            var permission = permissionServiceImpl.GetPermission(id);
            return View(permission);
        }
        [HttpPost]
        [NoAuthorizated("EditUiPermisson")]
        public ActionResult EditUiPermisson(PermissionDto permissionDto)
        {
            if (this.ModelState.IsValid)
            {
                permissionServiceImpl.UpdateUiPermission(permissionDto);
                ViewBag.PostState = 9;
            }
            return View();
        }
        [HttpGet]
        [NoAuthorizated("DeleteUiPermisson")]
        public ActionResult DeleteUiPermisson(Guid id)
        {
            permissionServiceImpl.DeleteUiPermission(id);
            return Content("ok");
        }
      
        /// <summary>
        /// 给用户授权
        /// </summary>
        /// <returns></returns>
         [NoAuthorizated("Authoriztion")]
        public ActionResult Authoriztion(Guid? userId)
        {
            return View();
        }
        [HttpGet]
        [NoAuthorizated("PermissionTreeDate")]
        public ActionResult PermissionTreeDate(Guid? roleId)
        {
           
            var allPermissionType = permissionServiceImpl.GetAllPermission().Where(t => t.IsEnableEdit).Select(t => t.TypeName).Where(t=>t!=null&&t.Trim().Length>0).Distinct();
           allPermissionType= allPermissionType.OrderBy(t => t.Substring(0,1));
            ViewBag.TypeNames = allPermissionType.Select(t=>t.Substring(1,t.Length-1));
            ViewBag.RoleId = roleId;
            return View();
        }
        [NoAuthorizated("SelectPermission")]
        public ActionResult SelectPermission(Guid operationId)
        {
            ViewBag.OperationId = operationId;
            return View();
        }
       /// <summary>
        /// 绑定操作下拉列表  [需要缓存]
       /// </summary>
        private void InitOperations()
        {
            ViewBag.OperationSource = permissionServiceImpl.GetAllOperations();
        }
        [NoAuthorizated("TreeDate")]
        public JsonResult TreeDate(string typeName,Guid? roleId)
        {

           
            var allPermission = permissionServiceImpl.GetAllPermission().Where(t=>t.IsEnableEdit).OrderByDescending(t => t.Order).ToList();

            #region 是否指定类别
            var _tn = "";
            if (!string.IsNullOrEmpty(typeName))
            {
                allPermission = allPermission.Where(t => (t.Level==1&& t.TypeName.Trim().Substring(1,t.TypeName.Trim().Length-1) == typeName.Trim())||(t.Level!=1)).ToList();
            }
            #endregion

            var permissions = allPermission.Where(p => p.Level == 1 && p.ParentId == p.Id);
            if (permissions == null || permissions.Count() == 0)//初始化一个根结点 i --不需要进行初始化
            {
                //var permissionRoot = new PermissionModel().InitPermissionRoot();
                //permissionRoot.OperationId = permissionServiceImpl.GetOperation("Add").Id;
                //permissionServiceImpl.AddPermission(permissionRoot);
                
            }
            var uiPermission = allPermission.Where(p => p.Level == 2&&p.Id!=p.ParentId&&p.UiPermission!=null).ToList(); 
            var permissonModel=new PermissionModel();
          
            #region 处理角色选中权限
            IList<Guid> selectPermissionIds = null;
            if (roleId != null)
            {
                Guid id;
                if (Guid.TryParse(roleId.Value.ToString(), out id))
                {
                    selectPermissionIds = permissionServiceImpl.GetSelectPermissionsOfRole(id);
                   // permissionViewModel = permissonModel.GetPermissionSelectHandler(permissionViewModel, selectPermissionIds, null);
                }
            }
            #endregion
            var permissionViewModel = permissonModel.GetAllPermissions(permissions, uiPermission, selectPermissionIds);
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            
            return Json(permissionViewModel, JsonRequestBehavior.AllowGet);
        }
         [NoAuthorizated("TreeMenuDate")]
        public JsonResult TreeMenuDate()
        {
            var permissions = permissionServiceImpl.GetAllPermission().OrderByDescending(t => t.Order);
            var newPermissions = permissions.Where(p => p.Level == 1&&p.ParentId==p.Id).ToList();
            var uiPermission = permissionServiceImpl.GetUiPermissions();

          //  uiPermission.Where(P=>P.Id
            //var newUiPermissions = permissions.Where(p => p.Level != 1).Select(p=>new{PName=p.Name})
            //    .Concat(uiPermission.Select(ui => new { Name = ui.ClientId, Id = ui.Id }));
               // .Select(p => new {Id= });

            IList<UiPermissionModel> result =( from a in uiPermission
                         from b in permissions
                         where a.Id == b.Id
                          select new UiPermissionModel { Name = a.ImagePath, Id = a.Id, ParentId = b.ParentId }).ToList();

            ;
           

            var permissonModel = new PermissionModel();
            var permissionViewModel = permissonModel.GetPermissions(newPermissions, result);
           
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            return Json(permissionViewModel, JsonRequestBehavior.AllowGet);
        }

        #region 辅助显示
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
         [NoAuthorizated("GetJsonOfPermissions")]
        public ActionResult GetJsonOfPermissions(Guid? menuId)
        {
            var permissions = permissionServiceImpl.GetAllPermission().Where(p => p.Level == 1 && p.ParentId == p.Id).OrderByDescending(t => t.Order); ;
            if (permissions != null && permissions.Count() != 0)
            {
                var jsonResult = permissions.Where(p=>p.Level==1).Select(p => new
                {
                    Key = p.Id,
                    Code = p.Code,
                    Name = p.Name
                });

                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"10\"}";
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                return Content(target);
            }
            return Content("");
        }
        #endregion

        /// <summary>
        /// 用户权限(授权)
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
         [NoAuthorizated("UserPermission")]
         public ActionResult UserPermission(Guid?uid)
         {
             return View();
         }
         [NoAuthorizated("UserTreeMenuDate")]
         public ActionResult UserTreeMenuDate( Guid? roleId)
         {
             string typeName = "全部";
             var permissions = permissionServiceImpl.GetAllPermission().Where(t => t.IsEnableEdit).OrderByDescending(t => t.Order);
             var newPermissions = permissions.Where(p => p.Level == 1 && p.ParentId == p.Id).ToList();
             var uiPermission = permissionServiceImpl.GetUiPermissions();

             //  uiPermission.Where(P=>P.Id
             //var newUiPermissions = permissions.Where(p => p.Level != 1).Select(p=>new{PName=p.Name})
             //    .Concat(uiPermission.Select(ui => new { Name = ui.ClientId, Id = ui.Id }));
             // .Select(p => new {Id= });

             IList<UiPermissionModel> result = (from a in uiPermission
                                                from b in permissions
                                                where a.Id == b.Id
                                                select new UiPermissionModel { Name = a.ImagePath, Id = a.Id, ParentId = b.ParentId }).ToList();

             ;

             #region 处理角色选中权限
             IList<Guid> selectPermissionIds = null;
             if (roleId != null && !roleId.Equals(Guid.Empty))
             {
                 Guid id;
                 if (Guid.TryParse(roleId.Value.ToString(), out id))
                 {
                     selectPermissionIds = permissionServiceImpl.GetSelectPermissionsOfRole(id);
                     // permissionViewModel = permissonModel.GetPermissionSelectHandler(permissionViewModel, selectPermissionIds, null);
                 }
             }
             #endregion
             var permissonModel = new PermissionModel();
             var permissionViewModel = permissonModel.GetUserPermissions(newPermissions, result, selectPermissionIds);

            // Response.Cache.SetCacheability(HttpCacheability.NoCache);
             //return Json(permissionViewModel, JsonRequestBehavior.AllowGet);
            



             var target = Newtonsoft.Json.JsonConvert.SerializeObject(permissionViewModel);
             target = "{\"Rows\":" + target + ",\"Total\":\"" + result.Count() + "\"}";
             
             return Content(target);
         }
    }
}
